package com.loan.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.loan.entity.Menu;
import com.loan.entity.Role;
import com.loan.exception.RoleNameCationException;
import com.loan.mappers.RoleMapper;
import com.loan.mappers.RolePermMapper;
import com.loan.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * YJS
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RolePermMapper rolePermMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 添加角色权限表
     * @param role
     * @param permids
     */
    @Override
    public void add(Role role, Integer[] permids) {
        Role byRoleName = roleMapper.getByRoleName(role.getName());
        if(byRoleName != null){
                throw new RoleNameCationException("角色名:__" + role.getName()  + "__ 已存在 ");
        }
        role.setStatus(Role.ENABLE);
        roleMapper.addRole(role);
        for(int per : permids){
            rolePermMapper.add(role.getId(),per);
        }
    }

    /**
     * 修改角色权限表
     * @param role
     * @param perms
     */
    @Override
    public void updateRolePerm(Role role,Integer[] perms){
        Role byRoleName = roleMapper.getByRoleName(role.getName());
        if(byRoleName != null && byRoleName.getId() != role.getId()){
            throw new RoleNameCationException("角色名重复");
        }

        roleMapper.updateRole(role);
        rolePermMapper.delByRoleId(role.getId());
        for(int perm : perms){
            rolePermMapper.add(role.getId(),perm);
        }
    }

    /**
     * 根据校色id删除角色员工表，逻辑删除，数据库状态改为n
     * @param roleid
     */
    @Override
    public void deleteRoleId(int roleid) {
        Role byRoleId = roleMapper.getByRoleId(roleid);
        if(byRoleId == null){
            throw new RoleNameCationException("账号不存在或已被删除");
        }
        roleMapper.deleteRoleId(roleid);
    }

    @Override
    public List<Role> getRoleAll() {
        List<Role> roleAll = roleMapper.getRoleAll();
        return roleAll;
    }

    @Override
    public List<Role> getRoleall() {
        return roleMapper.getRoleall();
    }

    @Override
    public List<Role> selectbyrole(Role role) {
        List<Role> roles = roleMapper.selectByRole(role);
        return roles;
    }


}
